<template>
  <div class="study-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="container">
        <Breadcrumb :items="breadcrumbItems" />
        
        <div class="header-content">
          <div class="course-info">
            <div class="course-cover">
              <img :src="course?.cover || '/default-course.jpg'" :alt="course?.title" />
              <div class="course-progress-overlay">
                <div class="progress-circle">
                  <el-progress
                    type="circle"
                    :percentage="courseProgress"
                    :width="60"
                    :stroke-width="4"
                    color="#67c23a"
                  />
                </div>
              </div>
            </div>
            
            <div class="course-details">
              <h1 class="course-title">{{ course?.title }}</h1>
              <p class="course-subtitle">{{ course?.subtitle }}</p>
              
              <div class="course-meta">
                <div class="meta-item">
                  <el-icon><User /></el-icon>
                  <span>{{ course?.instructor?.name }}</span>
                </div>
                <div class="meta-item">
                  <el-icon><Clock /></el-icon>
                  <span>{{ formatDuration(course?.duration) }}</span>
                </div>
                <div class="meta-item">
                  <el-icon><Document /></el-icon>
                  <span>{{ course?.chapters?.length || 0 }} 章节</span>
                </div>
                <div class="meta-item">
                  <el-icon><VideoPlay /></el-icon>
                  <span>{{ totalLessons }} 课时</span>
                </div>
              </div>
              
              <div class="study-stats">
                <div class="stat-item">
                  <div class="stat-value">{{ studyTime }}</div>
                  <div class="stat-label">学习时长</div>
                </div>
                <div class="stat-item">
                  <div class="stat-value">{{ completedLessons }}/{{ totalLessons }}</div>
                  <div class="stat-label">完成课时</div>
                </div>
                <div class="stat-item">
                  <div class="stat-value">{{ courseProgress }}%</div>
                  <div class="stat-label">学习进度</div>
                </div>
              </div>
            </div>
          </div>
          
          <div class="header-actions">
            <el-button
              v-if="!isCompleted"
              type="primary"
              size="large"
              @click="continueStudy"
            >
              <el-icon><VideoPlay /></el-icon>
              继续学习
            </el-button>
            
            <el-button
              v-else
              type="success"
              size="large"
              @click="reviewCourse"
            >
              <el-icon><Refresh /></el-icon>
              复习课程
            </el-button>
            
            <el-dropdown trigger="click">
              <el-button>
                <el-icon><More /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="downloadCourse">
                    <el-icon><Download /></el-icon>
                    下载课程
                  </el-dropdown-item>
                  <el-dropdown-item @click="shareCourse">
                    <el-icon><Share /></el-icon>
                    分享课程
                  </el-dropdown-item>
                  <el-dropdown-item @click="addToFavorites">
                    <el-icon><Star /></el-icon>
                    收藏课程
                  </el-dropdown-item>
                  <el-dropdown-item divided @click="reportIssue">
                    <el-icon><Warning /></el-icon>
                    反馈问题
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 主要内容 -->
    <div class="main-content">
      <div class="container">
        <div class="content-layout">
          <!-- 左侧课程内容 -->
          <div class="content-sidebar">
            <div class="sidebar-header">
              <h3>课程目录</h3>
              <div class="sidebar-actions">
                <el-button
                  text
                  :class="{ active: expandAll }"
                  @click="toggleExpandAll"
                >
                  {{ expandAll ? '收起全部' : '展开全部' }}
                </el-button>
              </div>
            </div>
            
            <div class="course-outline">
              <div
                v-for="(chapter, chapterIndex) in course?.chapters"
                :key="chapter.id"
                class="chapter-item"
              >
                <div
                  class="chapter-header"
                  @click="toggleChapter(chapterIndex)"
                >
                  <div class="chapter-info">
                    <el-icon class="expand-icon" :class="{ expanded: expandedChapters.includes(chapterIndex) }">
                      <ArrowRight />
                    </el-icon>
                    <span class="chapter-title">{{ chapter.title }}</span>
                  </div>
                  
                  <div class="chapter-meta">
                    <span class="chapter-progress">
                      {{ getChapterProgress(chapter) }}%
                    </span>
                    <span class="chapter-duration">
                      {{ formatDuration(getChapterDuration(chapter)) }}
                    </span>
                  </div>
                </div>
                
                <div
                  v-show="expandedChapters.includes(chapterIndex)"
                  class="chapter-lessons"
                >
                  <div
                    v-for="(lesson, lessonIndex) in chapter.lessons"
                    :key="lesson.id"
                    class="lesson-item"
                    :class="{
                      active: currentLesson?.id === lesson.id,
                      completed: isLessonCompleted(lesson.id),
                      locked: isLessonLocked(lesson.id)
                    }"
                    @click="selectLesson(lesson)"
                  >
                    <div class="lesson-icon">
                      <el-icon v-if="isLessonCompleted(lesson.id)" class="completed-icon">
                        <Check />
                      </el-icon>
                      <el-icon v-else-if="isLessonLocked(lesson.id)" class="locked-icon">
                        <Lock />
                      </el-icon>
                      <el-icon v-else-if="lesson.type === 'video'" class="video-icon">
                        <VideoPlay />
                      </el-icon>
                      <el-icon v-else-if="lesson.type === 'document'" class="document-icon">
                        <Document />
                      </el-icon>
                      <el-icon v-else class="quiz-icon">
                        <EditPen />
                      </el-icon>
                    </div>
                    
                    <div class="lesson-info">
                      <div class="lesson-title">{{ lesson.title }}</div>
                      <div class="lesson-meta">
                        <span class="lesson-duration">{{ formatDuration(lesson.duration) }}</span>
                        <span v-if="lesson.type === 'quiz'" class="lesson-type">练习</span>
                      </div>
                    </div>
                    
                    <div class="lesson-actions">
                      <el-button
                        v-if="!isLessonLocked(lesson.id)"
                        text
                        size="small"
                        @click.stop="previewLesson(lesson)"
                      >
                        预览
                      </el-button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 右侧学习区域 -->
          <div class="study-area">
            <div v-if="!currentLesson" class="empty-state">
              <div class="empty-icon">
                <el-icon><VideoPlay /></el-icon>
              </div>
              <h3>选择课程开始学习</h3>
              <p>从左侧课程目录中选择一个课时开始学习</p>
              <el-button type="primary" @click="startFirstLesson">
                开始第一课
              </el-button>
            </div>
            
            <div v-else class="lesson-content">
              <!-- 课时头部 -->
              <div class="lesson-header">
                <div class="lesson-info">
                  <h2 class="lesson-title">{{ currentLesson.title }}</h2>
                  <div class="lesson-meta">
                    <span class="lesson-type">{{ getLessonTypeText(currentLesson.type) }}</span>
                    <span class="lesson-duration">{{ formatDuration(currentLesson.duration) }}</span>
                  </div>
                </div>
                
                <div class="lesson-actions">
                  <el-button
                    v-if="hasPreviousLesson"
                    @click="previousLesson"
                  >
                    <el-icon><ArrowLeft /></el-icon>
                    上一课
                  </el-button>
                  
                  <el-button
                    v-if="hasNextLesson"
                    type="primary"
                    @click="nextLesson"
                  >
                    下一课
                    <el-icon><ArrowRight /></el-icon>
                  </el-button>
                  
                  <el-button
                    v-if="!hasNextLesson && !isLessonCompleted(currentLesson.id)"
                    type="success"
                    @click="completeLesson"
                  >
                    完成学习
                  </el-button>
                </div>
              </div>
              
              <!-- 课时内容 -->
              <div class="lesson-body">
                <!-- 视频课时 -->
                <div v-if="currentLesson.type === 'video'" class="video-lesson">
                  <div class="video-player">
                    <video
                      ref="videoPlayer"
                      :src="currentLesson.videoUrl"
                      controls
                      preload="metadata"
                      @timeupdate="onVideoTimeUpdate"
                      @ended="onVideoEnded"
                    >
                      您的浏览器不支持视频播放
                    </video>
                  </div>
                  
                  <div class="video-controls">
                    <div class="playback-speed">
                      <span>播放速度：</span>
                      <el-select v-model="playbackSpeed" @change="changePlaybackSpeed">
                        <el-option label="0.5x" value="0.5" />
                        <el-option label="0.75x" value="0.75" />
                        <el-option label="1.0x" value="1.0" />
                        <el-option label="1.25x" value="1.25" />
                        <el-option label="1.5x" value="1.5" />
                        <el-option label="2.0x" value="2.0" />
                      </el-select>
                    </div>
                    
                    <div class="video-quality">
                      <span>清晰度：</span>
                      <el-select v-model="videoQuality">
                        <el-option label="流畅" value="360p" />
                        <el-option label="标清" value="480p" />
                        <el-option label="高清" value="720p" />
                        <el-option label="超清" value="1080p" />
                      </el-select>
                    </div>
                  </div>
                </div>
                
                <!-- 文档课时 -->
                <div v-else-if="currentLesson.type === 'document'" class="document-lesson">
                  <div class="document-content" v-html="currentLesson.content"></div>
                </div>
                
                <!-- 练习课时 -->
                <div v-else-if="currentLesson.type === 'quiz'" class="quiz-lesson">
                  <div class="quiz-header">
                    <h3>课时练习</h3>
                    <div class="quiz-info">
                      <span>共 {{ currentLesson.questions?.length || 0 }} 题</span>
                      <span>限时 {{ currentLesson.timeLimit }} 分钟</span>
                    </div>
                  </div>
                  
                  <div class="quiz-content">
                    <div
                      v-for="(question, index) in currentLesson.questions"
                      :key="question.id"
                      class="question-item"
                    >
                      <div class="question-header">
                        <span class="question-number">{{ index + 1 }}.</span>
                        <span class="question-text">{{ question.text }}</span>
                      </div>
                      
                      <div class="question-options">
                        <el-radio-group
                          v-if="question.type === 'single'"
                          v-model="quizAnswers[question.id]"
                        >
                          <el-radio
                            v-for="option in question.options"
                            :key="option.id"
                            :label="option.id"
                            class="option-item"
                          >
                            {{ option.text }}
                          </el-radio>
                        </el-radio-group>
                        
                        <el-checkbox-group
                          v-else-if="question.type === 'multiple'"
                          v-model="quizAnswers[question.id]"
                        >
                          <el-checkbox
                            v-for="option in question.options"
                            :key="option.id"
                            :label="option.id"
                            class="option-item"
                          >
                            {{ option.text }}
                          </el-checkbox>
                        </el-checkbox-group>
                        
                        <el-input
                          v-else
                          v-model="quizAnswers[question.id]"
                          type="textarea"
                          placeholder="请输入答案"
                          :rows="3"
                        />
                      </div>
                    </div>
                    
                    <div class="quiz-actions">
                      <el-button type="primary" @click="submitQuiz">
                        提交答案
                      </el-button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 学习笔记侧边栏 -->
    <div class="notes-sidebar" :class="{ open: showNotes }">
      <div class="notes-header">
        <h3>学习笔记</h3>
        <el-button text @click="toggleNotes">
          <el-icon><Close /></el-icon>
        </el-button>
      </div>
      
      <div class="notes-content">
        <div class="note-editor">
          <el-input
            v-model="newNote"
            type="textarea"
            placeholder="记录学习心得..."
            :rows="4"
          />
          <el-button type="primary" size="small" @click="addNote">
            添加笔记
          </el-button>
        </div>
        
        <div class="notes-list">
          <div
            v-for="note in notes"
            :key="note.id"
            class="note-item"
          >
            <div class="note-content">{{ note.content }}</div>
            <div class="note-meta">
              <span class="note-time">{{ formatTime(note.createdAt) }}</span>
              <el-button text size="small" @click="deleteNote(note.id)">
                删除
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 笔记按钮 -->
    <div class="floating-actions">
      <el-button
        type="primary"
        circle
        size="large"
        class="notes-toggle"
        @click="toggleNotes"
      >
        <el-icon><EditPen /></el-icon>
      </el-button>
    </div>
    
    <!-- 加载状态 -->
    <Loading v-if="loading" />
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  User, Clock, Document, VideoPlay, More, Download, Share, Star, Warning,
  ArrowRight, ArrowLeft, Check, Lock, EditPen, Refresh, Close
} from '@element-plus/icons-vue'
import { useCourseStore } from '@/stores/course'
import { useUserStore } from '@/stores/user'
import Breadcrumb from '@/components/common/Breadcrumb.vue'
import Loading from '@/components/common/Loading.vue'
import { formatDuration, formatTime } from '@/utils/format'

const route = useRoute()
const router = useRouter()
const courseStore = useCourseStore()
const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const course = ref(null)
const currentLesson = ref(null)
const expandedChapters = ref([])
const expandAll = ref(false)
const showNotes = ref(false)
const playbackSpeed = ref('1.0')
const videoQuality = ref('720p')
const quizAnswers = reactive({})
const newNote = ref('')
const notes = ref([])
const videoPlayer = ref(null)

// 面包屑导航
const breadcrumbItems = computed(() => [
  { title: '首页', path: '/' },
  { title: '我的课程', path: '/profile?tab=courses' },
  { title: course.value?.title || '课程学习' }
])

// 计算属性
const totalLessons = computed(() => {
  if (!course.value?.chapters) return 0
  return course.value.chapters.reduce((total, chapter) => {
    return total + (chapter.lessons?.length || 0)
  }, 0)
})

const completedLessons = computed(() => {
  if (!course.value?.progress?.completedLessons) return 0
  return course.value.progress.completedLessons.length
})

const courseProgress = computed(() => {
  if (totalLessons.value === 0) return 0
  return Math.round((completedLessons.value / totalLessons.value) * 100)
})

const studyTime = computed(() => {
  const minutes = course.value?.progress?.studyTime || 0
  const hours = Math.floor(minutes / 60)
  const mins = minutes % 60
  return hours > 0 ? `${hours}h ${mins}m` : `${mins}m`
})

const isCompleted = computed(() => {
  return courseProgress.value === 100
})

const hasPreviousLesson = computed(() => {
  if (!currentLesson.value) return false
  const { chapterIndex, lessonIndex } = getCurrentLessonIndex()
  return chapterIndex > 0 || lessonIndex > 0
})

const hasNextLesson = computed(() => {
  if (!currentLesson.value) return false
  const { chapterIndex, lessonIndex } = getCurrentLessonIndex()
  const chapter = course.value.chapters[chapterIndex]
  
  // 当前章节还有下一课
  if (lessonIndex < chapter.lessons.length - 1) return true
  
  // 还有下一章节
  return chapterIndex < course.value.chapters.length - 1
})

// 方法
const loadCourse = async () => {
  try {
    loading.value = true
    const courseId = route.params.id
    
    // 加载课程详情和学习进度
    course.value = await courseStore.getCourseDetail(courseId)
    
    // 加载学习笔记
    await loadNotes()
    
    // 初始化展开的章节
    if (course.value.chapters?.length > 0) {
      expandedChapters.value = [0] // 默认展开第一章
    }
    
    // 如果有上次学习的课时，自动选择
    const lastLesson = getLastStudiedLesson()
    if (lastLesson) {
      currentLesson.value = lastLesson
    }
    
  } catch (error) {
    ElMessage.error('加载课程失败')
    console.error('Load course error:', error)
  } finally {
    loading.value = false
  }
}

const getLastStudiedLesson = () => {
  if (!course.value?.progress?.lastLessonId) return null
  
  for (const chapter of course.value.chapters) {
    const lesson = chapter.lessons.find(l => l.id === course.value.progress.lastLessonId)
    if (lesson) return lesson
  }
  
  return null
}

const toggleChapter = (chapterIndex) => {
  const index = expandedChapters.value.indexOf(chapterIndex)
  if (index > -1) {
    expandedChapters.value.splice(index, 1)
  } else {
    expandedChapters.value.push(chapterIndex)
  }
}

const toggleExpandAll = () => {
  expandAll.value = !expandAll.value
  if (expandAll.value) {
    expandedChapters.value = course.value.chapters.map((_, index) => index)
  } else {
    expandedChapters.value = []
  }
}

const getChapterProgress = (chapter) => {
  if (!chapter.lessons?.length) return 0
  const completed = chapter.lessons.filter(lesson => 
    isLessonCompleted(lesson.id)
  ).length
  return Math.round((completed / chapter.lessons.length) * 100)
}

const getChapterDuration = (chapter) => {
  if (!chapter.lessons?.length) return 0
  return chapter.lessons.reduce((total, lesson) => total + (lesson.duration || 0), 0)
}

const isLessonCompleted = (lessonId) => {
  return course.value?.progress?.completedLessons?.includes(lessonId) || false
}

const isLessonLocked = (lessonId) => {
  // 简单的顺序解锁逻辑
  if (!course.value?.chapters) return false
  
  let foundCurrent = false
  for (const chapter of course.value.chapters) {
    for (const lesson of chapter.lessons) {
      if (lesson.id === lessonId) {
        foundCurrent = true
        break
      }
      if (!isLessonCompleted(lesson.id)) {
        return true // 前面有未完成的课时，当前课时被锁定
      }
    }
    if (foundCurrent) break
  }
  
  return false
}

const selectLesson = (lesson) => {
  if (isLessonLocked(lesson.id)) {
    ElMessage.warning('请先完成前面的课时')
    return
  }
  
  currentLesson.value = lesson
  
  // 记录学习进度
  courseStore.updateLastLesson(course.value.id, lesson.id)
}

const getCurrentLessonIndex = () => {
  if (!currentLesson.value || !course.value?.chapters) {
    return { chapterIndex: -1, lessonIndex: -1 }
  }
  
  for (let chapterIndex = 0; chapterIndex < course.value.chapters.length; chapterIndex++) {
    const chapter = course.value.chapters[chapterIndex]
    const lessonIndex = chapter.lessons.findIndex(l => l.id === currentLesson.value.id)
    if (lessonIndex > -1) {
      return { chapterIndex, lessonIndex }
    }
  }
  
  return { chapterIndex: -1, lessonIndex: -1 }
}

const previousLesson = () => {
  const { chapterIndex, lessonIndex } = getCurrentLessonIndex()
  
  if (lessonIndex > 0) {
    // 当前章节的上一课
    const lesson = course.value.chapters[chapterIndex].lessons[lessonIndex - 1]
    selectLesson(lesson)
  } else if (chapterIndex > 0) {
    // 上一章节的最后一课
    const prevChapter = course.value.chapters[chapterIndex - 1]
    const lesson = prevChapter.lessons[prevChapter.lessons.length - 1]
    selectLesson(lesson)
  }
}

const nextLesson = () => {
  const { chapterIndex, lessonIndex } = getCurrentLessonIndex()
  const chapter = course.value.chapters[chapterIndex]
  
  if (lessonIndex < chapter.lessons.length - 1) {
    // 当前章节的下一课
    const lesson = chapter.lessons[lessonIndex + 1]
    selectLesson(lesson)
  } else if (chapterIndex < course.value.chapters.length - 1) {
    // 下一章节的第一课
    const nextChapter = course.value.chapters[chapterIndex + 1]
    const lesson = nextChapter.lessons[0]
    selectLesson(lesson)
  }
}

const startFirstLesson = () => {
  if (course.value?.chapters?.[0]?.lessons?.[0]) {
    selectLesson(course.value.chapters[0].lessons[0])
    
    // 展开第一章
    if (!expandedChapters.value.includes(0)) {
      expandedChapters.value.push(0)
    }
  }
}

const continueStudy = () => {
  const lastLesson = getLastStudiedLesson()
  if (lastLesson) {
    selectLesson(lastLesson)
  } else {
    startFirstLesson()
  }
}

const reviewCourse = () => {
  startFirstLesson()
}

const completeLesson = async () => {
  try {
    await courseStore.completeLesson(course.value.id, currentLesson.value.id)
    
    // 更新本地进度
    if (!course.value.progress.completedLessons.includes(currentLesson.value.id)) {
      course.value.progress.completedLessons.push(currentLesson.value.id)
    }
    
    ElMessage.success('课时完成！')
    
    // 自动进入下一课
    if (hasNextLesson.value) {
      setTimeout(() => {
        nextLesson()
      }, 1000)
    }
    
  } catch (error) {
    ElMessage.error('完成课时失败')
  }
}

const previewLesson = (lesson) => {
  // 预览功能
  ElMessage.info('预览功能开发中...')
}

const getLessonTypeText = (type) => {
  const typeMap = {
    video: '视频',
    document: '文档',
    quiz: '练习'
  }
  return typeMap[type] || '未知'
}

// 视频相关方法
const onVideoTimeUpdate = (event) => {
  const video = event.target
  const progress = (video.currentTime / video.duration) * 100
  
  // 记录观看进度
  courseStore.updateVideoProgress(course.value.id, currentLesson.value.id, {
    currentTime: video.currentTime,
    duration: video.duration,
    progress
  })
}

const onVideoEnded = () => {
  // 视频播放完成，自动标记为已完成
  if (!isLessonCompleted(currentLesson.value.id)) {
    completeLesson()
  }
}

const changePlaybackSpeed = () => {
  if (videoPlayer.value) {
    videoPlayer.value.playbackRate = parseFloat(playbackSpeed.value)
  }
}

// 练习相关方法
const submitQuiz = async () => {
  try {
    const answers = Object.keys(quizAnswers).map(questionId => ({
      questionId,
      answer: quizAnswers[questionId]
    }))
    
    const result = await courseStore.submitQuiz(course.value.id, currentLesson.value.id, answers)
    
    ElMessageBox.alert(
      `答题完成！得分：${result.score}/${result.totalScore}`,
      '练习结果',
      {
        confirmButtonText: '确定',
        type: result.passed ? 'success' : 'warning'
      }
    )
    
    if (result.passed) {
      completeLesson()
    }
    
  } catch (error) {
    ElMessage.error('提交答案失败')
  }
}

// 笔记相关方法
const toggleNotes = () => {
  showNotes.value = !showNotes.value
}

const loadNotes = async () => {
  try {
    notes.value = await courseStore.getCourseNotes(course.value.id)
  } catch (error) {
    console.error('Load notes error:', error)
  }
}

const addNote = async () => {
  if (!newNote.value.trim()) return
  
  try {
    const note = await courseStore.addCourseNote(course.value.id, {
      content: newNote.value,
      lessonId: currentLesson.value?.id,
      timestamp: videoPlayer.value?.currentTime || 0
    })
    
    notes.value.unshift(note)
    newNote.value = ''
    
    ElMessage.success('笔记添加成功')
  } catch (error) {
    ElMessage.error('添加笔记失败')
  }
}

const deleteNote = async (noteId) => {
  try {
    await courseStore.deleteCourseNote(noteId)
    notes.value = notes.value.filter(note => note.id !== noteId)
    ElMessage.success('笔记删除成功')
  } catch (error) {
    ElMessage.error('删除笔记失败')
  }
}

// 其他操作
const downloadCourse = () => {
  ElMessage.info('下载功能开发中...')
}

const shareCourse = () => {
  ElMessage.info('分享功能开发中...')
}

const addToFavorites = async () => {
  try {
    await courseStore.toggleFavorite(course.value.id)
    ElMessage.success('已添加到收藏')
  } catch (error) {
    ElMessage.error('收藏失败')
  }
}

const reportIssue = () => {
  ElMessage.info('反馈功能开发中...')
}

// 生命周期
onMounted(() => {
  loadCourse()
})

// 监听路由变化
watch(
  () => route.params.id,
  (newId) => {
    if (newId) {
      loadCourse()
    }
  }
)

// 监听当前课时变化，自动展开对应章节
watch(
  currentLesson,
  (newLesson) => {
    if (!newLesson || !course.value?.chapters) return
    
    for (let chapterIndex = 0; chapterIndex < course.value.chapters.length; chapterIndex++) {
      const chapter = course.value.chapters[chapterIndex]
      if (chapter.lessons.some(l => l.id === newLesson.id)) {
        if (!expandedChapters.value.includes(chapterIndex)) {
          expandedChapters.value.push(chapterIndex)
        }
        break
      }
    }
  }
)

// 页面离开时保存学习进度
onUnmounted(() => {
  if (currentLesson.value && videoPlayer.value) {
    courseStore.updateVideoProgress(course.value.id, currentLesson.value.id, {
      currentTime: videoPlayer.value.currentTime,
      duration: videoPlayer.value.duration,
      progress: (videoPlayer.value.currentTime / videoPlayer.value.duration) * 100
    })
  }
})
</script>

<style lang="scss" scoped>
.study-page {
  min-height: 100vh;
  background: var(--el-bg-color-page);
}

// 页面头部
.page-header {
  background: var(--el-bg-color);
  border-bottom: 1px solid var(--el-border-color-lighter);
  padding: 20px 0;
  
  .header-content {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    gap: 32px;
    margin-top: 16px;
  }
  
  .course-info {
    display: flex;
    gap: 20px;
    flex: 1;
    
    .course-cover {
      position: relative;
      width: 120px;
      height: 80px;
      border-radius: 8px;
      overflow: hidden;
      flex-shrink: 0;
      
      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
      
      .course-progress-overlay {
        position: absolute;
        top: 0;
        right: 0;
        background: rgba(0, 0, 0, 0.7);
        border-radius: 0 8px 0 8px;
        padding: 8px;
        
        .progress-circle {
          :deep(.el-progress-circle__text) {
            color: white;
            font-size: 12px;
          }
        }
      }
    }
    
    .course-details {
      flex: 1;
      
      .course-title {
        font-size: 1.5rem;
        font-weight: 600;
        color: var(--el-text-color-primary);
        margin-bottom: 8px;
        line-height: 1.3;
      }
      
      .course-subtitle {
        color: var(--el-text-color-secondary);
        margin-bottom: 16px;
        line-height: 1.4;
      }
      
      .course-meta {
        display: flex;
        gap: 24px;
        margin-bottom: 16px;
        
        .meta-item {
          display: flex;
          align-items: center;
          gap: 6px;
          color: var(--el-text-color-regular);
          font-size: 14px;
          
          .el-icon {
            color: var(--el-color-primary);
          }
        }
      }
      
      .study-stats {
        display: flex;
        gap: 32px;
        
        .stat-item {
          text-align: center;
          
          .stat-value {
            font-size: 1.2rem;
            font-weight: 600;
            color: var(--el-color-primary);
            margin-bottom: 4px;
          }
          
          .stat-label {
            font-size: 12px;
            color: var(--el-text-color-secondary);
          }
        }
      }
    }
  }
  
  .header-actions {
    display: flex;
    gap: 12px;
    align-items: flex-start;
  }
}

// 主要内容
.main-content {
  padding: 24px 0;
  
  .content-layout {
    display: grid;
    grid-template-columns: 320px 1fr;
    gap: 24px;
    align-items: flex-start;
  }
}

// 左侧边栏
.content-sidebar {
  background: var(--el-bg-color);
  border-radius: 8px;
  border: 1px solid var(--el-border-color-lighter);
  overflow: hidden;
  
  .sidebar-header {
    padding: 16px 20px;
    border-bottom: 1px solid var(--el-border-color-lighter);
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    h3 {
      margin: 0;
      font-size: 16px;
      font-weight: 600;
      color: var(--el-text-color-primary);
    }
    
    .sidebar-actions {
      .el-button {
        &.active {
          color: var(--el-color-primary);
        }
      }
    }
  }
  
  .course-outline {
    max-height: calc(100vh - 300px);
    overflow-y: auto;
  }
}

// 章节项目
.chapter-item {
  border-bottom: 1px solid var(--el-border-color-lighter);
  
  &:last-child {
    border-bottom: none;
  }
  
  .chapter-header {
    padding: 16px 20px;
    cursor: pointer;
    display: flex;
    justify-content: space-between;
    align-items: center;
    transition: background-color 0.2s;
    
    &:hover {
      background: var(--el-fill-color-light);
    }
    
    .chapter-info {
      display: flex;
      align-items: center;
      gap: 8px;
      
      .expand-icon {
        transition: transform 0.2s;
        
        &.expanded {
          transform: rotate(90deg);
        }
      }
      
      .chapter-title {
        font-weight: 500;
        color: var(--el-text-color-primary);
      }
    }
    
    .chapter-meta {
      display: flex;
      gap: 12px;
      font-size: 12px;
      color: var(--el-text-color-secondary);
    }
  }
  
  .chapter-lessons {
    background: var(--el-fill-color-lighter);
  }
}

// 课时项目
.lesson-item {
  padding: 12px 20px 12px 48px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 12px;
  transition: all 0.2s;
  border-bottom: 1px solid var(--el-border-color-extra-light);
  
  &:last-child {
    border-bottom: none;
  }
  
  &:hover {
    background: var(--el-fill-color);
  }
  
  &.active {
    background: var(--el-color-primary-light-9);
    border-left: 3px solid var(--el-color-primary);
    
    .lesson-title {
      color: var(--el-color-primary);
      font-weight: 500;
    }
  }
  
  &.completed {
    .lesson-icon .completed-icon {
      color: var(--el-color-success);
    }
  }
  
  &.locked {
    opacity: 0.6;
    cursor: not-allowed;
    
    .lesson-icon .locked-icon {
      color: var(--el-text-color-disabled);
    }
  }
  
  .lesson-icon {
    width: 20px;
    height: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
    
    .el-icon {
      font-size: 16px;
    }
    
    .video-icon {
      color: var(--el-color-primary);
    }
    
    .document-icon {
      color: var(--el-color-warning);
    }
    
    .quiz-icon {
      color: var(--el-color-info);
    }
  }
  
  .lesson-info {
    flex: 1;
    min-width: 0;
    
    .lesson-title {
      font-size: 14px;
      color: var(--el-text-color-primary);
      margin-bottom: 4px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    
    .lesson-meta {
      display: flex;
      gap: 8px;
      font-size: 12px;
      color: var(--el-text-color-secondary);
      
      .lesson-type {
        background: var(--el-color-info-light-8);
        color: var(--el-color-info);
        padding: 2px 6px;
        border-radius: 4px;
      }
    }
  }
  
  .lesson-actions {
    opacity: 0;
    transition: opacity 0.2s;
  }
  
  &:hover .lesson-actions {
    opacity: 1;
  }
}

// 学习区域
.study-area {
  background: var(--el-bg-color);
  border-radius: 8px;
  border: 1px solid var(--el-border-color-lighter);
  overflow: hidden;
  
  .empty-state {
    padding: 80px 40px;
    text-align: center;
    
    .empty-icon {
      width: 80px;
      height: 80px;
      margin: 0 auto 24px;
      background: var(--el-fill-color-light);
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      
      .el-icon {
        font-size: 32px;
        color: var(--el-text-color-secondary);
      }
    }
    
    h3 {
      font-size: 1.2rem;
      color: var(--el-text-color-primary);
      margin-bottom: 8px;
    }
    
    p {
      color: var(--el-text-color-secondary);
      margin-bottom: 24px;
    }
  }
}

// 课时内容
.lesson-content {
  .lesson-header {
    padding: 20px 24px;
    border-bottom: 1px solid var(--el-border-color-lighter);
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    gap: 24px;
    
    .lesson-info {
      flex: 1;
      
      .lesson-title {
        font-size: 1.3rem;
        font-weight: 600;
        color: var(--el-text-color-primary);
        margin-bottom: 8px;
        line-height: 1.3;
      }
      
      .lesson-meta {
        display: flex;
        gap: 16px;
        font-size: 14px;
        color: var(--el-text-color-secondary);
        
        .lesson-type {
          background: var(--el-color-primary-light-8);
          color: var(--el-color-primary);
          padding: 4px 8px;
          border-radius: 4px;
          font-size: 12px;
        }
      }
    }
    
    .lesson-actions {
      display: flex;
      gap: 12px;
    }
  }
  
  .lesson-body {
    padding: 24px;
  }
}

// 视频课时
.video-lesson {
  .video-player {
    margin-bottom: 20px;
    
    video {
      width: 100%;
      height: auto;
      border-radius: 8px;
      background: #000;
    }
  }
  
  .video-controls {
    display: flex;
    gap: 24px;
    align-items: center;
    
    .playback-speed,
    .video-quality {
      display: flex;
      align-items: center;
      gap: 8px;
      font-size: 14px;
      color: var(--el-text-color-regular);
      
      .el-select {
        width: 80px;
      }
    }
  }
}

// 文档课时
.document-lesson {
  .document-content {
    line-height: 1.8;
    color: var(--el-text-color-primary);
    
    :deep(h1), :deep(h2), :deep(h3), :deep(h4), :deep(h5), :deep(h6) {
      margin: 24px 0 16px 0;
      color: var(--el-text-color-primary);
    }
    
    :deep(p) {
      margin-bottom: 16px;
    }
    
    :deep(img) {
      max-width: 100%;
      height: auto;
      border-radius: 4px;
      margin: 16px 0;
    }
    
    :deep(code) {
      background: var(--el-fill-color-light);
      padding: 2px 6px;
      border-radius: 4px;
      font-family: 'Monaco', 'Consolas', monospace;
    }
    
    :deep(pre) {
      background: var(--el-fill-color-light);
      padding: 16px;
      border-radius: 8px;
      overflow-x: auto;
      margin: 16px 0;
    }
  }
}

// 练习课时
.quiz-lesson {
  .quiz-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    padding-bottom: 16px;
    border-bottom: 1px solid var(--el-border-color-lighter);
    
    h3 {
      margin: 0;
      color: var(--el-text-color-primary);
    }
    
    .quiz-info {
      display: flex;
      gap: 16px;
      font-size: 14px;
      color: var(--el-text-color-secondary);
    }
  }
  
  .question-item {
    margin-bottom: 32px;
    padding: 20px;
    background: var(--el-fill-color-lighter);
    border-radius: 8px;
    
    .question-header {
      display: flex;
      gap: 8px;
      margin-bottom: 16px;
      
      .question-number {
        font-weight: 600;
        color: var(--el-color-primary);
        flex-shrink: 0;
      }
      
      .question-text {
        color: var(--el-text-color-primary);
        line-height: 1.5;
      }
    }
    
    .question-options {
      .option-item {
        margin-bottom: 12px;
        
        :deep(.el-radio__label),
        :deep(.el-checkbox__label) {
          line-height: 1.5;
        }
      }
    }
  }
  
  .quiz-actions {
    text-align: center;
    padding-top: 24px;
    border-top: 1px solid var(--el-border-color-lighter);
  }
}

// 笔记侧边栏
.notes-sidebar {
  position: fixed;
  top: 0;
  right: -400px;
  width: 400px;
  height: 100vh;
  background: var(--el-bg-color);
  border-left: 1px solid var(--el-border-color-lighter);
  z-index: 1000;
  transition: right 0.3s;
  display: flex;
  flex-direction: column;
  
  &.open {
    right: 0;
  }
  
  .notes-header {
    padding: 16px 20px;
    border-bottom: 1px solid var(--el-border-color-lighter);
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    h3 {
      margin: 0;
      font-size: 16px;
      color: var(--el-text-color-primary);
    }
  }
  
  .notes-content {
    flex: 1;
    padding: 20px;
    overflow-y: auto;
    
    .note-editor {
      margin-bottom: 24px;
      
      .el-textarea {
        margin-bottom: 12px;
      }
    }
    
    .notes-list {
      .note-item {
        padding: 16px;
        background: var(--el-fill-color-lighter);
        border-radius: 8px;
        margin-bottom: 12px;
        
        .note-content {
          color: var(--el-text-color-primary);
          line-height: 1.5;
          margin-bottom: 8px;
        }
        
        .note-meta {
          display: flex;
          justify-content: space-between;
          align-items: center;
          font-size: 12px;
          color: var(--el-text-color-secondary);
        }
      }
    }
  }
}

// 浮动操作按钮
.floating-actions {
  position: fixed;
  bottom: 24px;
  right: 24px;
  z-index: 999;
  
  .notes-toggle {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  }
}

// 响应式设计
@media (max-width: 1200px) {
  .main-content {
    .content-layout {
      grid-template-columns: 280px 1fr;
    }
  }
  
  .notes-sidebar {
    width: 350px;
    right: -350px;
  }
}

@media (max-width: 1024px) {
  .page-header {
    .header-content {
      flex-direction: column;
      gap: 20px;
      
      .header-actions {
        align-self: stretch;
        justify-content: center;
      }
    }
    
    .course-info {
      .course-meta {
        flex-wrap: wrap;
        gap: 12px 20px;
      }
      
      .study-stats {
        gap: 20px;
      }
    }
  }
  
  .main-content {
    .content-layout {
      grid-template-columns: 1fr;
      
      .content-sidebar {
        order: 2;
      }
      
      .study-area {
        order: 1;
      }
    }
  }
}

@media (max-width: 768px) {
  .page-header {
    padding: 16px 0;
    
    .course-info {
      flex-direction: column;
      gap: 16px;
      
      .course-cover {
        align-self: center;
      }
      
      .course-details {
        text-align: center;
        
        .course-meta {
          justify-content: center;
        }
        
        .study-stats {
          justify-content: center;
        }
      }
    }
  }
  
  .main-content {
    padding: 16px 0;
    
    .content-layout {
      gap: 16px;
    }
  }
  
  .lesson-content {
    .lesson-header {
      padding: 16px 20px;
      flex-direction: column;
      gap: 16px;
      
      .lesson-actions {
        align-self: stretch;
        
        .el-button {
          flex: 1;
        }
      }
    }
    
    .lesson-body {
      padding: 20px;
    }
  }
  
  .video-lesson {
    .video-controls {
      flex-direction: column;
      gap: 16px;
      align-items: stretch;
      
      .playback-speed,
      .video-quality {
        justify-content: space-between;
        
        .el-select {
          width: 120px;
        }
      }
    }
  }
  
  .notes-sidebar {
    width: 100vw;
    right: -100vw;
  }
}

@media (max-width: 480px) {
  .page-header {
    .course-info {
      .course-details {
        .course-title {
          font-size: 1.2rem;
        }
        
        .course-meta {
          flex-direction: column;
          gap: 8px;
        }
        
        .study-stats {
          flex-direction: column;
          gap: 12px;
        }
      }
    }
  }
  
  .content-sidebar {
    .sidebar-header {
      padding: 12px 16px;
      
      h3 {
        font-size: 14px;
      }
    }
  }
  
  .chapter-item {
    .chapter-header {
      padding: 12px 16px;
      
      .chapter-title {
        font-size: 14px;
      }
    }
  }
  
  .lesson-item {
    padding: 10px 16px 10px 40px;
    
    .lesson-info {
      .lesson-title {
        font-size: 13px;
      }
    }
  }
  
  .lesson-content {
    .lesson-header {
      padding: 12px 16px;
      
      .lesson-title {
        font-size: 1.1rem;
      }
    }
    
    .lesson-body {
      padding: 16px;
    }
  }
  
  .quiz-lesson {
    .question-item {
      padding: 16px;
      
      .question-header {
        .question-text {
          font-size: 14px;
        }
      }
    }
  }
}
</style>